package com.ccit.springbootlaw.controller.base;

import com.ccit.springbootlaw.controller.resful.Code;
import com.ccit.springbootlaw.controller.resful.Result;
import com.ccit.springbootlaw.pojo.User;
import com.ccit.springbootlaw.service.UserService;
import com.ccit.springbootlaw.utils.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Result getUserById(@PathVariable int id) {
        User user = userService.findById(id);
        if (user != null) {
            return new Result(Code.GET_OK, user, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "用户不存在");
        }
    }

    /**
     * 根据邮箱查询用户
     */
    @GetMapping("/email/{email}")
    public Result getUserByEmail(@PathVariable String email) {
        User user = userService.findByEmail(email);
        if (user != null) {
            return new Result(Code.GET_OK, user, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "用户不存在");
        }
    }

    /**
     * 根据条件查询用户
     */
    @PostMapping("/search")
    public Result searchUsers(@RequestBody User user) {
        List<User> users = userService.findUsersByConditions(user);
        if (users != null && !users.isEmpty()) {
            return new Result(Code.GET_OK, users, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "未找到符合条件的用户");
        }
    }

    /**
     * 验证用户名、ID或邮箱和密码
     */
    @PostMapping("/login")
    public Result verifyUser(@RequestBody User user) {
        String text = user.getName();
        if (user.getId() == 0) {
            int id = 0;
            if (text.matches("\\d+")) {
                id = Integer.parseInt(text);
            }
            user.setId(id);
        }
        user.setEmail(text);
        User loginUser = userService.findUserByUsernameOrIdOrEmailAndVerifyPassword(user);
        if (loginUser != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", loginUser.getId());
            claims.put("userName", loginUser.getName());
            claims.put("userEmail", loginUser.getEmail());
            claims.put("userRole", loginUser.getRole());
            String token = JWTutil.generateToken(claims);
            //令牌存到redis中
            stringRedisTemplate.opsForValue().set(token, token, 1, TimeUnit.DAYS);
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userId", loginUser.getId());
            data.put("userRole", loginUser.getRole());
            data.put("userName", loginUser.getName());
            data.put("userEmail", loginUser.getEmail());
            return new Result(Code.VERIFY_OK, data, "登录成功");
        } else {
            return new Result(Code.VERIFY_ERR, null, "用户名或密码错误");
        }
    }

    /**
     * 验证用户名是否重复，用户名密码长度是否符合
     * 插入用户
     */
    @PostMapping("/enroll")
    public Result addUser(@RequestBody User user) {
        User user1 = new User();
        User user2 = new User();
        String name = user.getName();
        String password = user.getPassword();
        user1.setName(user.getName());
        user2.setEmail(user.getEmail());
        if ((name != null && name.length() >= 5 && name.length() <= 20) &&
                (password != null && password.length() >= 8 && password.length() <= 20)) {
            if (userService.findUsersByConditions(user1).size() != 0 || userService.findUsersByConditions(user2).size() != 0) {
                return new Result(Code.ADD_ERR, null, "用户名或邮箱已存在");
            }
            int result = userService.insertUser(user);
            if (result > 0) {
                return new Result(Code.ADD_OK, user, "添加成功");
            } else {
                return new Result(Code.ADD_ERR, null, "添加失败");
            }
        } else {
            return new Result(Code.ADD_ERR, null, "用户名或密码格式错误");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping
    public Result updateUser(@RequestBody User user, @RequestHeader("Authorization") String token) {
        if (user.getName() != null || user.getEmail() != null) {
            User user1 = new User();
            User user2 = new User();
            user1.setName(user.getName());
            user2.setEmail(user.getEmail());
            if (userService.findUsersByConditions(user1).size() != 0 || userService.findUsersByConditions(user2).size() != 0) {
                return new Result(Code.UPDATE_ERR, null, "用户名或邮箱已存在");
            }
        }
        int result = userService.updateUser(user);
        if (result > 0) {
            if (user.getPassword() != null && stringRedisTemplate.opsForValue().get(token).equals(token)) {
                stringRedisTemplate.delete(token);
            }
            return new Result(Code.UPDATE_OK, user, "更新成功");
        } else {
            return new Result(Code.UPDATE_ERR, null, "更新失败");
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable int id) {
        int result = userService.deleteUserById(id);
        if (result > 0) {
            return new Result(Code.DELETE_OK, null, "删除成功");
        } else {
            return new Result(Code.DELETE_ERR, null, "删除失败");
        }
    }

    /**
     * 查询所有用户
     */
    @GetMapping
    public Result getAllUsers() {
        List<User> users = userService.findAllUsers();
        if (users != null && !users.isEmpty()) {
            return new Result(Code.GET_OK, users, "查询成功");
        } else {
            return new Result(Code.GET_ERR, null, "未找到任何用户");
        }
    }
}